package com.pangyangyang.elasticsearch.plugin.jdbc.query;

import com.pangyangyang.elasticsearch.plugin.exception.MessageRiverException;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Arrays;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * Created by yangwang on 2015/1/22.
 */
public class QueryDataEntity {
    private String id;
    private String[] keys, values;
    private int size ;

    public QueryDataEntity() {
        keys = new String[10];
        values = new String[10];
        size = 0;
    }

    public void add(String key, String value){
        if(StringUtils.equals("_id", key)){
            id = value;
            return;
        }
        if(size == keys.length){
            String[] newKeys = new String[keys.length * 2];
            String[] newValues = new String[keys.length * 2];
            System.arraycopy(keys, 0, newKeys, 0, keys.length);
            System.arraycopy(values, 0, newValues, 0, values.length);
            this.keys = newKeys;
            this.values = newValues;
        }
        this.keys[size] = key;
        this.values[size ] = value;
        size++;

    }

    public String get(String key){
        for (int i = 0;  i < size; i++){
            if(StringUtils.equals(key, this.keys[i])){
                return this.values[i];
            }
        }
        return null;
    }

    public String toJsonDocument(){
        try{
            XContentBuilder builder = jsonBuilder().startObject();
            for(int i = 0; i < size; i++){
                builder.field(this.keys[i], this.values[i]);
            }
            builder.endObject();
            return builder.string();
        } catch (IOException e){
            throw new MessageRiverException("generate json document failed.", e);
        }

    }

    public String getId() {
        return id;
    }

    @Override
    public String toString() {
        return "QueryDataEntity{" +
                "id='" + id + '\'' +
                ", keys=" + Arrays.toString(keys) +
                ", values=" + Arrays.toString(values) +
                ", size=" + size +
                '}';
    }
}
